/**
 * Description...
 *
 * @author     mole <mole1230@gmail.com>
 * @version    $Id: app.js 72 2010-12-13 02:11:40Z mole1230 $
 */
(function($) {
	var App = {};
	
	/**
	 * 语言转换
	 */
	App.t = function(message, params) {
		return message;
	};
	
	/**
	 * Debug
	 */
	App.log = function(arg) {
		if (window.console) {
			window.console.log(arg);
		}
	};
	
	/**
	 * 表单验证并提交
	 */
	App.ajaxForm = function(selector, vSettings, fSettings) {
		fSettings = $.extend({
			cache: false,
			clearForm: false
		}, fSettings || {}, {
			dataType: 'json'
		});

		var oBeforeSubmit =  fSettings.beforeSubmit;
		var oSuccess = fSettings.success;
		var oError = fSettings.error;
		var oComplete = fSettings.complete;
		fSettings.beforeSubmit = function(arr, $form, options) {
			if (this.$form.data('__AJAX-UNCOMPLETE__')) {
				alert(App.t('本次请求还未完成，请不要重复提交'));
				return false;
			} else {
				this.$form.data('__AJAX-UNCOMPLETE__', true);
			}
			
			if ($.isFunction(oBeforeSubmit) && oBeforeSubmit.apply(this, arguments) === false) {
				return false;
			}
			
			return true;
		};
		fSettings.success = function(json, status, xhr, $form) {
			if ($.isFunction(oSuccess) && oSuccess.apply(this, arguments) === false) {
				return false;
			}
			
			if (/^A[0-9]{5}/.test(json.code)) {
				if (json.data.message) {
					alert(json.data.message);
				} else {
					alert(App.t(json.code));
				}
				if (json.data.url) {
					window.location = json.data.url;
				}
			} else {
				
			}
		};
		fSettings.error = function(xhr, status, e) {
			if ($.isFunction(oError) && oError.apply(this, arguments) === false) {
				return false;
			}
			alert(App.t('服务器内部错误'));
			App.log(arguments);
		};
		fSettings.complete = function(xhr, status) {
			$.isFunction(oComplete) && oComplete.apply(this, arguments);
			this.$form.data('__AJAX-UNCOMPLETE__', false);
		}
		
		vSettings = $.extend({
			debug: true,
			errorPlacement: $.noop
		}, vSettings || {}, {
			submitHandler: function(form) {
				var $form = $(form);
				
				fSettings.$form = $form;
				$form.ajaxSubmit(fSettings);
			}
		});

		$(selector).validate(vSettings);
	};
	
	/**
	 * 放入 window 对象，方便使用
	 */
	window.App = App;
	window.t = App.t;
})(jQuery);
